package magic8;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.sasl.SASLPlainMechanism;

public class InstantMessenger {
	static String domain = "gmail.com";
	static String account = "magic8ball0929";
	
	public static String getPassword(){		
		System.out.print("Please enter the password for magic8ball0929@gmail.com: ");
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		try {
			return br.readLine();
		} catch (IOException e) {
			System.out.println("Error!");
		}
		return null;
	}
	
	public static void run() throws XMPPException{
		String pwd = getPassword();
		
		ConnectionConfiguration conConf = new ConnectionConfiguration("talk.google.com", 5222, "googlemail.com");
		SASLAuthentication.registerSASLMechanism(1, "PLAIN", SASLPlainMechanism.class);

		XMPPConnection connection = new XMPPConnection(conConf);
		connection.connect();
		
		connection.login(account+"@gmail.com", pwd, "smack");
		
		connection.getChatManager().addChatListener(new ChatManagerListener(){
			@Override
			public void chatCreated(Chat arg0, boolean arg1) {
				arg0.addMessageListener(new MessageListener(){

					@Override
					public void processMessage(Chat arg0, Message arg1) {
						String response = ResponseCreator.getResponse(arg1.getBody());
						try {
							arg0.sendMessage(response);
						} catch (XMPPException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				
				});
			}
		});
		
		System.out.println("Magic 8 Ball is connected!");
		
		while(true){
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	
	public static void main(String[] args) throws XMPPException{
		run();
	}
}
